package avicti.bdp.das;

import avicit.bdp.common.service.dto.BdpColumnDTO;
import avicit.bdp.common.service.dto.BdpTableDTO;
import avicit.bdp.common.utils.DateUtils;
import avicit.platform6.core.rest.msg.ResponseMsg;
import avicti.bdp.TestUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class TableTest {
    private RestTemplate restTemplate = new RestTemplate();

    private static String tableName = "table_" + System.currentTimeMillis();
    private static String typeId = "typeId_" + System.currentTimeMillis();
    private static String projectId = "projectId_" + System.currentTimeMillis();

    /**
     * 所有用例执行前准备工作
     */
    @BeforeClass
    public static void init() {
        System.out.println("用例初始化...");
    }

    /**
     * 单个测试用例运行前准备工作
     */
    @Before
    public void setUp() {
        // TODO:
    }

    /**
     * 单个测试用例运行后销毁工作
     */
    @After
    public void tearDown() {
        // TODO:
    }

    /**
     * 所有用例执行完成后准备工作
     */
    @AfterClass
    public static void destory() {
        System.out.println("用例执行完成，开始清理...");
    }

    /***********************************************Begin 测试用例 ***********************************************/
    @Test(timeout = 5 * 60 * 1000)
    public void testFile() throws Exception {
        // 查询空间列表
        ResponseEntity<ResponseMsg> result = restTemplate.exchange(TestUtils.DDS_HOSTPORT + "/api/bdp/dds/project/getAllProjectList",
                HttpMethod.GET, TestUtils.buildGetHttpEntity(), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        List<Object> finalBody = (List<Object>) result.getBody().getResponseBody();
        if(finalBody != null && finalBody.size() > 0){
            LinkedHashMap<String, String> obj = (LinkedHashMap<String, String>) finalBody.get(0);
            projectId = obj.get("id");
        }

        // 查询根分类
        String startTime = DateUtils.getTodayStartTime();
        String endTime = DateUtils.getTodayEndTime();
        result = restTemplate.exchange(TestUtils.HOSTPORT + "/api/bdp/dms/das/commontype/findCommonType?type=dataTable&projectId="+projectId,
                HttpMethod.GET, TestUtils.buildGetHttpEntity(), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        finalBody = (List<Object>) result.getBody().getResponseBody();
        assertEquals(1, finalBody.size());

        LinkedHashMap<String, String> obj = (LinkedHashMap<String, String>) finalBody.get(0);
        String parentId = obj.get("id");
        String parentName = obj.get("name");
        System.out.println("分类 id = " + parentId + ",name = " + parentName);

        // 新增分类
        JSONObject paramData = new JSONObject();
        paramData.put("leaf", 1);
        paramData.put("name", "aaa");
        paramData.put("parentId", parentId);
        paramData.put("parentName", parentName);
        paramData.put("projectId", projectId);
        paramData.put("type", "dataTable");
        paramData.put("unfolded", 0);

        result = restTemplate.postForEntity(TestUtils.HOSTPORT + "/api/bdp/dms/das/commontype/insertCommonType",
                TestUtils.buildPostHttpEntity(paramData.toJSONString()), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        String type_id = (String) result.getBody().getResponseBody();
        System.out.println("新增的分类ID = " + type_id);

        // 修改分类
        paramData.put("id", type_id);
        paramData.put("actionKey", "edit");
        paramData.put("orderBy", 0);
        paramData.put("name", "aaa_1");
        result = restTemplate.postForEntity(TestUtils.HOSTPORT + "/api/bdp/dms/das/commontype/updateCommonType",
                TestUtils.buildPostHttpEntity(paramData.toJSONString()), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        // 删除分类
        JSONObject param0 = new JSONObject();
        param0.put("id", type_id);
        result = restTemplate.postForEntity(TestUtils.HOSTPORT + "/api/bdp/dms/das/commontype/deleteCommonType",
                TestUtils.buildPostHttpEntity(param0.toJSONString()), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        // 新增数据表
        JSONObject param = new JSONObject();
        param.put("cnName", "aaa");
        param.put("dataSourceId", TestUtils.MYSQL_DATASOURCE_ID);
        param.put("dataSourceType", "mysql");
        param.put("dataStorageFormat", "ORC");
        param.put("name", tableName);
        param.put("projectId", projectId);
        param.put("type", 1);
        param.put("typeId", typeId);
        param.put("typeName", "typeName");

        List<BdpColumnDTO> columnList = new ArrayList<>();
        BdpColumnDTO columnDTO = new BdpColumnDTO();
        columnDTO.setCnName("字段说明");
        columnDTO.setColumnLength(19);
        columnDTO.setColumnType("bigint");
        columnDTO.setKey("ef54cfde-0569-485a-8be8-18edf17d0300");
        columnDTO.setName("column_name");
        columnDTO.setNullable(1);
        columnDTO.setOrderBy(1);
        columnDTO.setPrimaryKey(0);
        columnDTO.setUniqueKey(0);
        columnList.add(columnDTO);
        param.put("columnList", columnList);

        result = restTemplate.postForEntity(TestUtils.HOSTPORT + "/api/bdp/dms/das/table/insertDataTable",
                TestUtils.buildPostHttpEntity(param.toJSONString()), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        // 获取列表
        result = restTemplate.exchange(TestUtils.HOSTPORT + "/api/bdp/dms/das/table/getListForModel?typeId=" + typeId+"&projectId="+projectId,
                HttpMethod.GET, TestUtils.buildGetHttpEntity(), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());

        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getBody().getResponseBody();
        finalBody = (List<Object>) map.get("result");
        String tableId = "";
        BdpTableDTO table = null;
        for (Object object : finalBody) {
            LinkedHashMap<String, String> tempObj = (LinkedHashMap<String, String>) object;
            table = JSON.parseObject(JSON.toJSONString(tempObj), BdpTableDTO.class);
            if (table.getName().equals(tableName)) {
                System.out.println("数据表名称:" + table.getName());
                tableId = table.getId();
                break;
            }
        }

        // 修改数据表
        if(table != null){
            result = restTemplate.postForEntity(TestUtils.HOSTPORT + "/api/bdp/dms/das/table/updateDataTable",
                    TestUtils.buildPostHttpEntity(JSON.toJSONString(table)), ResponseMsg.class);

            TestUtils.handleFailedRequest(result);
            assertEquals("200", result.getBody().getRetCode());
        }

        // 删除数据表
        JSONObject param1 = new JSONObject();
        param1.put("ids", tableId);
        param1.put("projectId", projectId);
        param1.put("typeId", typeId);
        result = restTemplate.postForEntity(TestUtils.HOSTPORT + "/api/bdp/dms/das/table/deleteDataTable",
                TestUtils.buildPostHttpEntity(param1.toJSONString()), ResponseMsg.class);

        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());
    }

}
